package com.demo.security.custom.handler;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import com.demo.security.model.Result;

/**
 * 401异常处理，即未登录<br>
 * Spring Security 中的异常主要分为两大类：一类是认证异常，另一类是授权相关的异常。<br>
 * 并且，其抛出异常的地方是在过滤器链中，如果你使用@ControllerAdvice是没有办法处理的
 */
//@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException, ServletException {
        log.error(">>>>> 401异常: {}", ex.getMessage());
        log.error(ex.getMessage(), ex);
        Result<Object> result = Result.failure(HttpServletResponse.SC_UNAUTHORIZED, "未认证(登录).");
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(200);
        PrintWriter out = response.getWriter();
        out.write(result.toString());
        out.flush();
        out.close();
    }
}